package com.zeta.plan.bloom;

import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClassName RedisBloomFilter
 * @Description TODO
 * @Author zeta
 * @Date 2022/3/1 15:14
 * @Version 1.0
 **/
@Component
public class RedisBloomFilter {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据给定的布隆过滤器添加值
     * @param bloomFilterHelper
     * @param key 布隆过滤器的key
     * @param value 值
     * @param <T 值的类型
     */
    public <T> void addByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为null");
        int[] hashOffset = bloomFilterHelper.murmurHashOffset(value);
        for (int offset : hashOffset) {
            redisTemplate.opsForValue().setBit(key, offset, true);
        }
    }

    /**
     * 判断给定的布隆过滤器中是否存在value
     * @param bloomFilterHelper
     * @param key 给定布隆过滤器的key
     * @param value 值
     * @param <T> 值的类型
     * @return
     */
    public <T> boolean includeByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为null");
        int[] hashOffset = bloomFilterHelper.murmurHashOffset(value);
        for (int offset : hashOffset) {
            if (!redisTemplate.opsForValue().getBit(key, offset)) {
                return false;
            }
        }
        return true;
    }





}
